package com.dly.blog.service.impl;

import cn.hutool.core.util.StrUtil;
import com.dly.blog.dto.email.EmailFileDTO;
import com.dly.blog.dto.email.EmailSendDTO;
import com.dly.blog.service.EmailService;
import com.dly.blog.utile.CollectionUtils;
import com.dly.blog.utile.FileUtils;
import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import jodd.util.StringPool;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;

/**
 * @Author: DaiLiYu
 * @Date: 2023/7/19 9:46
 */
@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.email.username:learnerdly@163.com}")
    private String from;

    @Value("${spring.email.sendName:浮生若梦}")
    private String personal;

    @Resource
    private ExecutorService executorService;

    @Override
    public void sendEmail(EmailSendDTO emailSendDto) {
        CompletableFuture.runAsync(()->{
            StopWatch stopWatch = new StopWatch("发送邮件");
            stopWatch.start("开始发送邮件");

            try {
                MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, StandardCharsets.UTF_8.name());
                messageHelper.setFrom(from, personal);

                //设置主题
                messageHelper.setSubject(emailSendDto.getSubject());
                //设置正文内容
                messageHelper.setText(emailSendDto.getMailText(), emailSendDto.isHtml());

                //遍历接收人
                for (String to : emailSendDto.getEmailToList()) {
                    messageHelper.addTo(to);
                }

                if (CollectionUtils.isNotEmpty(emailSendDto.getCcList())) {
                    //遍历抄送人
                    for (String cc : emailSendDto.getCcList()) {
                        messageHelper.addCc(cc);
                    }
                }

                if (CollectionUtils.isNotEmpty(emailSendDto.getFileList())) {
                    //遍历附件
                    for (EmailFileDTO dto : emailSendDto.getFileList()) {
                        messageHelper.addAttachment(StrUtil.join(StringPool.DOT, StrUtil.isNotEmpty(dto.getName()) ? dto.getName() : UUID.randomUUID().toString(), dto.getSuffix()), dto.getFile());
                    }
                }

                //发送
                javaMailSender.send(mimeMessage);
            }catch (Exception e){
                log.error("发送邮件失败：{}", e.getMessage());
                //清除文件
                close(emailSendDto.getFileList());
            }

            stopWatch.stop();
            log.info("发送邮件耗时：{}",stopWatch.prettyPrint());
        }, executorService);
    }

    private void close(List<EmailFileDTO> fileList){
        if(CollectionUtils.isNotEmpty(fileList)){
            fileList.forEach(f-> FileUtils.delete(f.getFile()));
        }
    }
}
